'use strict';

const Controller = require('egg').Controller;

class LoginController extends Controller {
  async login() {
    const {ctx} = this;
    let result = await ctx.service.login.login(ctx.request.body);
    if(result.token){
      let userinfo = {};
      userinfo.userId = result.data.userId;
      userinfo.roles = result.data.sys_roles.map(el=>el.roleId);
      userinfo.userName = result.data.userName;
      userinfo.deptId = result.data.deptId;
      const request = ctx.request;
      ctx.session.userinfo = userinfo;
      ctx.session.maxAge = 1000 * 60 * 60;
      let deviceAgent = request.headers["user-agent"];
      const agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
      let os = agentID ? agentID : "PC"
      await ctx.model.SysLogininfor.create({
        userName:result.data.userName,
        ipaddr:ctx.request.ip,
        msg:"登陆成功",
        os,
      })
    }
    delete result.data;
    ctx.body = {...result};
  }
  async getInfo(){
    const {ctx} = this;
    const user = await ctx.helper.getUser();
    let roles = [];
    if(user) {
      roles = user.roles.map(el=>el.roleKey)
    }
    this.ctx.body = {
      code:200,
      msg:"成功",
      user:user,
      permissions:["*:*:*"],
      roles:roles
    };
  }
  async logout(){
    const {ctx} = this;
    ctx.session.userinfo = null;
    return this.ctx.body = this.ctx.helper.formateResponse(null,undefined,'注销成功');
  }
  async getCodeImg(){
    const {ctx,app} = this;
    const result = await ctx.service.login.captchaImage();
    const token = app.jwt.sign({
      "code":result.text
    },app.config.jwt.secret,{
      expiresIn:"60s"
    });
    ctx.session.login_code = result.text;
    // ctx.session.maxAge = 1000 * 60 * 60;
    ctx.set({"Authorization":token});
    // ctx.res.setHeader("Content-Type","image/svg+xml");
    ctx.body = result.data;
  }
  async register(){
    this.ctx.body = "register";
  }
  async getRouter(){
    const {ctx} = this;

    let result = await ctx.service.menu.getMenuByRole();

    result = result.filter(el=>el.menuType !== "F");
    let routerList = await ctx.helper.handleTree(result,"menuId","parentId");

    ctx.body = ctx.helper.formateResponse(ctx.service.menu.formateRouter(routerList));
  }
}

module.exports = LoginController;
